package com.xcjh.opencv;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.Setting;

import java.awt.event.KeyEvent;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class KeyMap {
    static final String KV="VK_";
    static Map<String,String> keyMaps=new HashMap<>();
    static Map<String,Field> keyEventFileds= ReflectUtil.getFieldMap(KeyEvent.class);
    static {
        Map<String, Field> fieldMap = ReflectUtil.getFieldMap(KeyEvent.class);
        Map<String, Field> keys = fieldMap.entrySet().stream().filter(kv -> kv.getKey().startsWith(KV)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        for (Map.Entry<String, Field> kv: keys.entrySet()) {
            keyMaps.put(toKey(kv.getKey()),kv.getValue().getName());
        }
        /*
         * 配置自定义映射
         */
        Setting setting = new Setting("keyMap.properties");
        setting.forEach((key, value) -> keyMaps.put(toKey(key), KV + value));
        /*
         * 代码自定义映射自定义
         */
        keyMaps.put(",",KV +"COMMA");
        keyMaps.put("逗号",KV +"COMMA");
        keyMaps.put("]",KV +"CLOSE_BRACKET");
        keyMaps.put("[",KV +"OPEN_BRACKET");
        keyMaps.put("\\",KV +"BACK_SLASH");
        keyMaps.put("/",KV +"SLASH");
        keyMaps.put(".",KV +"PERIOD");

    }
    private static String toKey(String keyStr){
        return keyStr.toUpperCase().replace(KV,"").replace("_","");
    }

    public static int getKey(String input){
        input=toKey(input);
        String filed=keyMaps.get(input);
        if(StrUtil.isEmpty(filed)){
            throw new RuntimeException(input+" 不存在配置");
        }
        try {
            Field field = keyEventFileds.get(filed);
            return (int) ReflectUtil.getStaticFieldValue(field);
        }catch (Exception e){
            System.out.println(filed);
            e.printStackTrace();
            throw e;
        }

    }


}
